<!-- 数据追溯 -->
<template>
    <div class="app-container">
        <!-- 查询条件 -->
        <el-form :model="queryParams" label-position="right" inline ref="queryRef" >

            <el-form-item label="条码" prop="primaryCode">
                <el-input v-model="queryParams.primaryCode" placeholder="" clearable style="width: 240px"/>
            </el-form-item>
            <el-form-item label="时间">
                <!--  :default-time="defaultTime2" -->
                <el-date-picker v-model="queryParams.dateRange" style="width: 360px" type="datetimerange"
                :default-time="defaultTime2"
                value-format="YYYY-MM-DD HH:mm:ss" range-separator="-"
                    start-placeholder="" end-placeholder=""></el-date-picker>
            </el-form-item>
            

            <el-form-item>
                <el-button type="primary" icon="search" @click="QueryClick">{{ $t('btn.search') }}</el-button>
                <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
                
                <el-button type="warning" plain icon="Download" @click="handleExport" >
                    {{ $t('btn.export') }}
                    </el-button>
            </el-form-item>

            

        </el-form>



        <!-- 下方内容（左侧选择工站、右侧显示表格） -->
        <el-row style="flex: 1;display: flex; ">
            <!-- 工站列表 ，选择不同工站需要切换动态表格 -->
            <el-col :span="24" :xs="24" style="display: flex;">
                <div class="vertical-options">
                    <ul>
                        <li v-for="option in options" :key="option.tableName"
                            :class="{ 'selected': selectedValue === option.tableName }"
                            @click="selectedValue = option.tableName">
                            {{ option.notes }}
                        </li>
                    </ul>
                </div>
                <!-- 动态表格区域 -->
                <div class="table-container">
                    <div style="flex: 1;position: relative;">
                        <div class="table-fill">
                            <el-table height="100%" :data="tableData" :key="selectedValue" border style="width: 100%" v-loading="loading">
                                <el-table-column prop="sequenceId" label="采集编号" width="100" align="center" />
                                <el-table-column  v-for="column in tableColumns" :key="column.columnName"
                                    :prop="column.columnName" :label="column.notes" :width="column.width" align="center"  />
                            </el-table>
                        </div>
                    </div>
                    
                    
                    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
                </div>

            </el-col>
        </el-row>






    </div>
</template>

<script setup name="datarecords">
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance()
import request,{ downFile } from '@/utils/request'

const statusOptions = ref([])
const sexOptions = ref([])
proxy.getDicts('sys_normal_disable').then((response) => {
    statusOptions.value = response.data
})
proxy.getDicts('sys_user_sex').then((response) => {
    sexOptions.value = response.data
})
const defaultTime2 = [
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
] // '12:00:00', '08:00:00'
const queryRef = ref()
const options = ref([])
const today = dayjs()
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    sort: '',
    sortType: 'asc',
    limit: 10000,
    dateRange:[  today.startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    today.endOf('day').format('YYYY-MM-DD HH:mm:ss')],
    primaryCode:''

})

// 初始化加载第一个表的数据
onMounted(() => {
    loaded()
    //handleTableChange(selectedTable.value)
})

const selectedValue = ref(null);
const total = ref(0)
// 表格数据
const tableData = ref([])

// 表头配置
const tableColumns = ref([])
// 加载状态
const loading = ref(false)


watch(selectedValue, (a, b) => {
    console.log('selectedValue', selectedValue.value)
    //查询当前表格数据，动态列渲染
    if (selectedValue.value)
    {
        queryParams.pageNum=1
        handleTableChange(selectedValue.value)
    }
})



function loaded() {
    //查询工站信息
    request({
        url: '/run/plcconfig/getvirtualtables',
        method: 'post'
    }).then((res) => {
        // debugger
        options.value = res.data
        if (res.data.length > 0)
            selectedValue.value = res.data[0].tableName

    })
}


// 处理表切换
const handleTableChange = async (tableName) => {
    try {
        loading.value = true
       
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 120))
        // 这里应该是实际API调用，我们使用mock数据代替
        const tableInfo = await fetchTableData(tableName)

        // 从mock数据获取
        //const tableInfo = mockData[tableName]

        if (tableInfo) {
            tableColumns.value = tableInfo.columns.filter( a => a.isDisplay)
            tableData.value = tableInfo.data
            total.value = tableInfo.pagination.total

        } else {

            proxy.$modal.msgError(`未找到表 ${tableName} 的数据结构`)
        }
    } catch (error) {

        proxy.$modal.msgError(`加载表数据失败: ${error.message}`)
    } finally {
        loading.value = false
    }
}



// 实际项目中替换为真实的API调用函数
async function fetchTableData(tableName) {

    // 表单参数
    const body = getQueryBody()
    const res = await request({
        url: `/run/plcconfig/QueryCollectData/${tableName}`,
        method: 'post',
        data: body
    })
    const r = res.data
    console.log('fetchTableData', r)
    return r

    //return mockData[tableName] || { columns: [], data: [] }
}

function getQueryBody()
{
    const { dateRange ,pageNum,pageSize,primaryCode } = queryParams
    const body = { pageNum,pageSize,primaryCode }
    proxy.addDateRange(body, dateRange) 
    return body
}

const QueryClick = ()=>{
    queryParams.pageNum = 1
    handleQuery()
}

const handleQuery = ()=>{
  
    const { primaryCode ,beginTime ,endTime} = getQueryBody()
    const body = {primaryCode , beginTime,endTime}
    const hasValue = Object.values(body).some(value => value!== undefined && value!== null && String(value).trim()!== '')
    if(!hasValue)
    {
        resetTable()
        proxy.$modal.msgError('请至少输入1个查询条件')
        return
    }
    if (selectedValue.value)
        handleTableChange(selectedValue.value)
}

const resetTable = ()=>{
    tableData.value = []
    total.value = 0
}



const resetQuery = ()=>{
    queryParams.dateRange = []
    const date = dayjs()
queryParams.dateRange = [  date.startOf('day').format('YYYY-MM-DD HH:mm:ss'),
date.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
  proxy.resetForm('queryRef')
  QueryClick()
}
//导出，必须有查询条件 ，
const handleExport =async ()=>{
    const body1  = getQueryBody()
    console.log('body1',body1)
    const { primaryCode ,beginTime ,endTime} = body1
    const body = {primaryCode , beginTime,endTime}
    const hasValue = Object.values(body).some(value => value!== undefined && value!== null && String(value).trim()!== '')
    if(!hasValue)
    {
        proxy.$modal.msgError('请至少输入1个查询条件')
        return
    }

    //提交导出
    await downFile('/run/plcconfig/ExportCollectData', { ...body })

}

</script>
<style scoped>
.app-container {
    display: flex;
    flex: 1;
    position: relative;
    box-sizing: border-box;
    flex-direction: column;
    padding-top: 10px;
    padding-bottom: 10px;
}

.vertical-options ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-wrap: nowrap;
    padding-right: 10px;
    flex-direction: column;
}

.vertical-options li {
    padding: 10px 15px;
    display: inline-block;
    background-color: white;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s ease;
    border: 1px solid #eee;
    /* 外边框 */
    white-space: nowrap;
}

.vertical-options li:hover {
    background-color: #f5f5f5;
    border-bottom: 1px solid #eee;
    /* 浅灰色边框 */
}

/* 最后一个li不需要底部边框 */
.vertical-options li:last-child {
    border-bottom: none;
}

.vertical-options li.selected {
    background-color: #1e90ff;
    color: white;
}

.table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    padding-bottom: 10px;
    gap: 5px;
    box-sizing: border-box;
}
.table-fill{
    
    position: absolute;
    height: 100%;
    width: 100%;
    overflow: hidden;
}
</style>